package com.trump.baiduim.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * @author guoyuans
 */
@Configuration
@Slf4j
public class EncryptUtil {

    private static final String ENCRYPT_ALGORITH = "AES";
    private static final String RANDOM_ALGORITH = "SHA1PRNG";
    private KeyGenerator keyGen;
    private SecureRandom secureRandom;

    /**
     * 对登陆密码转为md5，与数据库中密码对比
     *
     * @param pass 明文密码
     * @return md5加密后的密码
     * @throws Exception
     */
    public String encryptPassword(String pass) throws Exception {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(pass.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            log.error("md5值存在错误", e);
            return null;
        }
    }

    /**
     * 生成加密和解密的salt
     *
     * @return
     */
    public String generateSalt() {
        return String.valueOf((int) (Math.random() * 900000 + 100000));
    }

    /**
     * 对消息内容进行AES加密
     *
     * @param content 消息内容
     * @param key     加密密钥
     * @return
     */
    public String encryptMessage(String content, String key) {
        try {
            keyGen = KeyGenerator.getInstance(ENCRYPT_ALGORITH);
            secureRandom = SecureRandom.getInstance(RANDOM_ALGORITH);
            secureRandom.setSeed(key.getBytes());
            keyGen.init(128, secureRandom);
            SecretKey secretKey = keyGen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, ENCRYPT_ALGORITH);
            Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITH);
            byte[] bytes = content.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] byteResult = cipher.doFinal(bytes);

            StringBuffer stringBuffer = new StringBuffer();
            for (byte i : byteResult) {
                String hex = Integer.toHexString(i & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                stringBuffer.append(hex.toUpperCase());
            }
            return stringBuffer.toString();
        } catch (Exception e) {
            log.error("加密出现错误，请检查选择的加密算法与编码方式...", e);
        }
        return null;
    }

    /**
     * 对消息内容进行解密
     *
     * @param content 加密的密文
     * @param key     加密密钥
     * @return
     */
    public String decryptMessage(String content, String key) {
        if (content.length() < 1) {
            log.error("传入了空的密文");
            return null;
        }
        byte[] byteResult = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            byteResult[i] = (byte) (high * 16 + low);
        }

        try {
            keyGen = KeyGenerator.getInstance(ENCRYPT_ALGORITH);
            secureRandom = SecureRandom.getInstance(RANDOM_ALGORITH);
            secureRandom.setSeed(key.getBytes());
            keyGen.init(128, secureRandom);
            SecretKey secretKey = keyGen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, ENCRYPT_ALGORITH);
            Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITH);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(byteResult);
            return new String(result, "UTF-8");
        } catch (Exception e) {
            log.error("密文解密过程中出现错误，请检查...", e);
        }
        return null;
    }


}
